﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using System.Windows;
using Security.Events;
using Security.Events.Commands;
using Security.Events.Handlers;
using Security.View;

namespace Security.App
{
    public partial class SecurityApplication : Application
    {
        private CompositionContainer container;

        protected override void OnStartup(StartupEventArgs e)
        {
            Compose();
            InitializeHandlers();
            
            var mainView = container.GetExportedValue<IMainView>();
            MainWindow = mainView.MainWindow;

            if (ShowConnectionView())
                ShowMainView();
            else
                Shutdown();
            
            base.OnStartup(e);
        }

        private void InitializeHandlers()
        {
            foreach (var handler in container.GetExportedValues<CommandHandler>()){}
        }

        private void ShowMainView()
        {
            MainWindow.Show();
        }

        private bool ShowConnectionView()
        {
            var eventBroker = container.GetExportedValue<EventBroker>();
            var command = new ShowConnectionViewCommand();
            eventBroker.Publish(command);
            return command.DialogResult;
        }

        private void Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(GetApplicationStartupPath()));

            container = new CompositionContainer(catalog);
            var batch = new CompositionBatch();
            batch.AddPart(this);

            try
            {
                container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
            }
        }

        private string GetApplicationStartupPath()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var fileInfo = new FileInfo(assembly.Location);
            return fileInfo.DirectoryName;
        }
    }
}
